package com.lgl.mes.test;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;

public class SquareGrid {

    public static void main(String[] args) throws IOException {
        // 输入16个小块的面积
        //double[] areas = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40};

        double[] areas = {92.5,105,97.5,82.5,63,42.5,58,76,120,53,47,71,77.5,83.5,77.5,87.5};

        // 计算总面积
        double totalArea = 0;
        for (double area : areas) {
            totalArea += area;
        }

        // 计算正方形的边长
        double sideLength = Math.sqrt(totalArea);

        // 创建一个BufferedImage对象
        BufferedImage image = new BufferedImage((int)sideLength, (int)sideLength, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();
        g2d.setBackground(Color.WHITE);
        g2d.clearRect(0, 0, (int)sideLength, (int)sideLength);

        // 定义颜色列表
        Color[] colors = new Color[] {
                Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW,
                Color.CYAN, Color.MAGENTA, Color.ORANGE, Color.PINK,
                Color.LIGHT_GRAY, Color.GRAY, Color.DARK_GRAY, Color.BLACK,
                Color.WHITE, Color.RED.darker(), Color.GREEN.darker(), Color.BLUE.darker()
        };

        // 计算每个小块的尺寸
        double blockWidth = sideLength / 4;
        double blockHeight = sideLength / 4;

        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                // 计算小块的位置
                double x = i * blockWidth;
                double y = j * blockHeight;

                // 随机选择颜色
                Color color = colors[i * 4 + j];
                g2d.setColor(color);

                // 绘制小块
                g2d.fillRect((int)x, (int)y, (int)blockWidth, (int)blockHeight);

                // 绘制面积文字
                //g2d.setColor(Color.BLACK);
                //g2d.drawString(String.format("%.1f", areas[i * 4 + j]), (float)(x + blockWidth / 2), (float)(y + blockHeight / 2));
            }
        }

        // 保存图像到文件
        ImageIO.write(image, "png", new File("square_grid_java.png"));
        g2d.dispose();

        System.out.println("Image saved as square_grid_java.png");
    }
}
